package cn.wzb;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置对象：
 * RabbitMQ的配置类
 * 1.交换机
 * 2.接受短信的队列
 * 3.接受邮件的队列
 * 4.绑定短信的队列到交换机
 * 5.绑定邮件的队列到交换机
 * ===========================
 * 6.发送者发消息
 * 7.邮件消息消费
 * 8.短信消息消费
 */
@Configuration
public class RabbitMQConfig {
    //队列：邮件
    public static final String NAME_QUEUE_EMAIL_1107 = "name_queue_email_1107";
    //队列：短信
    public static final String NAME_QUEUE_SMS_1107 = "name_queue_sms_1107";
    //交换机
    public static final String NAME_EXCHANGE_TOPICS_1107 = "name_exchange_topics_1107";

    //1.交换机
    /**
     * 交换机配置
     * ExchangeBuilder提供了fanout、direct、topic、header交换机类型的配置
     * @return the exchange
     */
    @Bean(NAME_EXCHANGE_TOPICS_1107)   //Spring容器中的bean的名字
    public Exchange exchange() {
        //durable(true)持久化，消息队列重启后交换机仍然存在
        //参数：RabbitmQ中的交换机的名字 ， 持久化
        return ExchangeBuilder.topicExchange(NAME_EXCHANGE_TOPICS_1107).durable(true).build();
    }
    //2.接受短信的队列
    @Bean(NAME_QUEUE_SMS_1107)  //Spring容器中的bean的名字
    public Queue smsQueue() {
        Queue queue = new Queue(NAME_QUEUE_SMS_1107,true);   //RabbitMQ中的队列名
        return queue;
    }
    //3.接受邮件的队列
    @Bean(NAME_QUEUE_EMAIL_1107)  //Spring容器中的bean的名字
    public Queue emailQueue() {
        Queue queue = new Queue(NAME_QUEUE_EMAIL_1107,true);   //RabbitMQ中的队列名
        return queue;
    }

    //4.绑定短信的队列到交换机
    /**
     * channel.queueBind(INFORM_QUEUE_SMS,"inform_exchange_topic","inform.#.sms.#");
     * 绑定队列到交换机 .
     * @param queue    the queue
     * @param exchange the exchange
     * @return the binding
     */
    @Bean
    public Binding bindingSMSQueue(@Qualifier(NAME_QUEUE_SMS_1107) Queue queue,
                                   @Qualifier(NAME_EXCHANGE_TOPICS_1107) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("sms.#").noargs();
    }
    //5.绑定邮件的队列到交换机
    @Bean
    public Binding bindingEmailQueue(@Qualifier(NAME_QUEUE_EMAIL_1107) Queue queue,
                                     @Qualifier(NAME_EXCHANGE_TOPICS_1107) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("email.#").noargs();
    }
}
